import axios from 'axios';

/**
 * 附近位置最大最小经纬度计算 
 * @param   latitude   纬度
 * @param   longitude  经度
 * @param   distince    距离（千米）
 * @returns 格式：经度最小值 经度最大值 纬度最小值 纬度最大值
 */
export const getMaxMinLngLat = function (latitude, longitude, distince) {
  let r = 6371393;    // 地球半径米
  let lng = longitude;
  let lat = latitude;
  let dlng = 2 * Math.asin(Math.sin(distince / (2 * r)) / Math.cos(lat * Math.PI / 180));
  dlng = dlng * 180 / Math.PI;// 角度转为弧度
  let dlat = distince / r;
  dlat = dlat * 180 / Math.PI;
  let minlat = lat - dlat;
  let maxlat = lat + dlat;
  let minlng = lng - dlng;
  let maxlng = lng + dlng;
  return [minlng, maxlng, minlat, maxlat];
}

/**
 * 根据多个regoncode查找政区边界的geojson数据
 * @param {*} list 多政区
 * @param {*} type 1 返回政区边界 2 返回政区下子级的边界 3 都返回 若是多个政区返回多个政区的边界
 * @returns arr
 * 
 * async 返回的是Promise对象,async里return xxx 相当于 return Promise.resolve(xxx)
 */
export const getRegionjson = async function (list, type) {
  if (list.length === 1) {
    if (type === 1) {
      // 此处相当于return Promise.resolve(getRegionBorder(list))
      // getRegionBorder返回的是Promise对象，此处就相当于resolve了
      return [await getRegionBorder(list)]
    } else if (type === 2) {
      return [await getRegionChildrensBorder(list)]
    } else if (type === 3) {
      // await的后面如果是Promise对象，那么await的返回值就是Promise对象的resolve/reject返回结果。
      return [await getRegionBorder(list), await getRegionChildrensBorder(list)]
    } else {
      return null
    }
  } else {
    let curcodes = list.map((r) => Number(r.code));
    let res = await axios.get('/json/region.json');
    let pset = new Set()
    res.data.forEach((item) => {
      if (curcodes.includes(Number(item.code))) {
        pset.add(Number(item.pcode))
      }
    });
    let pcodes = Array.from(pset)
    let plist = pcodes.map((pc) => axios.get(`/json/${pc === 1 ? 100000 : pc}.json`));
    let result = await Promise.all(plist);
    let json = {
      type: 'FeatureCollection',
      features: []
    };
    for (let rs of result) {
      let arr = rs.data.features;
      let rlt = arr.filter((item) => curcodes.includes(item.properties.adcode));
      json.features.push(...rlt);
    }
    return [json]
  }
}

export const getRegionBorder = async function (list) {
  let cur = list[0];
  let { code, pcode } = cur;
  pcode = pcode == '1' ? 100000 : pcode;
  if (code == '1') {
    return null
  } else {
    let rsd = await axios.get(`/json/${pcode}.json`)
    let arr = rsd.data.features;
    return arr.find((item) => item.properties.adcode == code)
  }
}

export const getSubRegioncode = function (code) {
  let codex = code;
  if (code.endsWith('0000')) {
    codex = code.replace('0000', '');
  } else if (code.endsWith('00')) {
    codex = code.replace('00', '');
  }
  return codex;
}

const getRegionChildrensBorder = async function (list) {
  let cur = list[0];
  let subcode = getSubRegioncode(cur.code)
  if (subcode.length > 5) {
    return null
  } else {
    let result = await axios.get(`/json/${cur.code == '1' ? 100000 : cur.code}.json`);
    return result.data;
  }
}

export const rangeColor = ["#d8f1d9", "#aee1ae", "#8fd690", "#40a341", "#40a341"];

export function getColorRange(max, min, num, type = "float") {
  let newmin = Math.floor(min);
  let newmax = Math.ceil(max);
  let gap =
    type === "int"
      ? parseInt((newmax - newmin) / num)
      : ((newmax - newmin) / num).toFixed(2);
  if (gap === 0) {
    let obj = {
      min: newmin,
      max: newmax,
      color: rangeColor[0],
    };
    return [obj];
  }
  let fobj = [];
  for (let i = 0; i < num; i++) {
    let obj = {};
    obj.min = newmin + gap * i;
    obj.max = i === num - 1 ? null : obj.min + Number(gap);
    obj.color = rangeColor[i];
    fobj[i] = obj;
  }
  return fobj;
}